package api

import (
	"fmt"
	"gitee.com/DengAnbang/Wefore/src/bean"
	"gitee.com/DengAnbang/Wefore/src/code"
	"gitee.com/DengAnbang/goutils/fileUtil"
	"gitee.com/DengAnbang/goutils/httpUtils"
	"gitee.com/DengAnbang/goutils/loge"
	"gitee.com/DengAnbang/goutils/update"
	"net/http"
	"net/url"
	"os"
)

var (
	UploadWorkTime = "/UploadWorkTime"
	GetWorkTime    = "/GetWorkTime"
	//公共部分
	PublicDatabaseBackups = "/public/database/backups"
	PublicDatabaseRestore = "/public/database/restore"
	PublicFileUpload      = "/public/file/upload"
	PublicFileDelete      = "/public/file/delete"
	PublicFileUploadChat  = "/public/file/upload/chat"
	//用户相关
	UserRegister                 = "/pc/user/register"
	UserLogin                    = "/pc/user/login"
	UserUpdate                   = "/pc/user/update"
	UserDelete                   = "/pc/user/delete"
	UserSelectAll                = "/pc/user/select/all"
	UserSelect                   = "/pc/user/select"
	UserToStructureTreeAdd       = "/pc/user/to/structure/tree"
	UserToStructureTreeSelectAll = "/pc/user/to/structure/tree/select/all"
	//权限相关
	PermissionAdd                   = "/pc/permission/add"
	PermissionUpdate                = "/pc/permission/update"
	PermissionDelete                = "/pc/permission/delete"
	PermissionSelect                = "/pc/permission/select"
	PermissionSelectList            = "/pc/permission/select/list"
	PermissionToStructureTreeAdd    = "/pc/permission/structure/add"
	PermissionToStructureTreeDelete = "/pc/permission/structure/delete"
	PermissionToStructureTreeSelect = "/pc/permission/structure/select"
	CharacterAdd                    = "/pc/permission/character/add"
	CharacterSelectAll              = "/pc/permission/character/select/all"
	CharacterDelete                 = "/pc/permission/character/delete"
	//组织结构树相关
	StructureTreeNodeCreate         = "/pc/structure/treeNode/create"
	StructureTreeNodeDelete         = "/pc/structure/treeNode/delete"
	StructureTreeNodeUpdate         = "/pc/structure/treeNode/update"
	StructureTreeNodeSelectChild    = "/pc/structure/treeNode/select/child"
	StructureTreeNodeSelectChildAll = "/pc/structure/treeNode/select/child/all"
	//文件树相关
	FileTreeNodeCreate             = "/pc/file/treeNode/create"
	FileTreeNodeDelete             = "/pc/file/treeNode/delete"
	FileTreeNodeUpdate             = "/pc/file/treeNode/update"
	FileTreeNodeSelectChild        = "/pc/file/treeNode/select/child"
	FileTreeNodeSelectChildAll     = "/pc/file/treeNode/select/child/all"
	FileTreeFileAdd                = "/pc/file/treeNode/file/add"
	FileTreeFileSelect             = "/pc/file/treeNode/file/select"
	FileTreeFileCommissioned       = "/pc/file/treeNode/file/commissioned"
	FileTreeFileCommissionedSelect = "/pc/file/treeNode/file/commissioned/select"
	//项目树相关
	ProjectTreeNodeCreate         = "/pc/project/treeNode/create"
	ProjectTreeNodeCreateApplyFor = "/pc/project/treeNode/create/applyFor"
	ProjectTreeNodeAddStructure   = "/pc/project/treeNode/add/structure"
	ProjectTreeNodeDelete         = "/pc/project/treeNode/delete"
	ProjectTreeNodeUpdate         = "/pc/project/treeNode/update"
	ProjectTreeChildNodeSelect    = "/pc/project/treeNode/select/child"
	ProjectTreeChildNodeSelectAll = "/pc/project/treeNode/select/child/all"
	ProjectTreeUserAdd            = "/pc/project/treeNode/user/add"
	ProjectTreeUserDelete         = "/pc/project/treeNode/user/delete"
	ProjectTreeUserSelect         = "/pc/project/treeNode/user/select"
	ProjectTreeUserSelectAll      = "/pc/project/treeNode/user/select/all"
	ProjectTreeUserSelectProject  = "/pc/project/treeNode/user/select/project"
	//考勤相关
	AttendancePunchIn                   = "/pc/attendance/punch/in"
	AttendancePunchOut                  = "/pc/attendance/punch/out"
	AttendanceSelect                    = "/pc/attendance/select"
	AttendanceAskForLeaveCreate         = "/pc/attendance/askForLeave/create"
	AttendanceAskForLeaveSelectById     = "/pc/attendance/askForLeave/select/id"
	AttendanceAskForLeaveSelectByUserId = "/pc/attendance/askForLeave/select/userId"
	AttendanceAskForLeaveApproval       = "/pc/attendance/askForLeave/approval"
	AttendanceAskForLeaveApprovalSelect = "/pc/attendance/askForLeave/approval/select"
	//消息相关
	MessageSelect = "/pc/message/select"
	MessageRead   = "/pc/message/read"
	MessageDelete = "/pc/message/delete"
	//聊天消息相关
	ChatMessageSend       = "/pc/message/chat/send"
	ChatMessageDelete     = "/pc/message/chat/delete"
	ChatMessageSelectTome = "/pc/message/chat/select/tome"
	//合同相关
	ContractCreate           = "/pc/contract/create"
	ContractUpdate           = "/pc/contract/update"
	ContractDelete           = "/pc/contract/delete"
	ContractSelectByNo       = "/pc/contract/select/no"
	ContractSelectByVague    = "/pc/contract/select/vague"
	ContractSelectByTime     = "/pc/contract/select/time"
	ContractAdditionalAdd    = "/pc/contract/additional/add"
	ContractAdditionalSelect = "/pc/contract/additional/select"
	ContractAdditionalUpdate = "/pc/contract/additional/update"
	ContractAdditionalDelete = "/pc/contract/additional/delete"
	ContractTypeCreate       = "/pc/contract/type/create"
	ContractTypeSelectAll    = "/pc/contract/type/select/all"
	ContractYearSelectAll    = "/pc/contract/year/select/all"
	ContractTypeDelete       = "/pc/contract/type/delete"
	WorkTypeCreate           = "/pc/work/type/create"
	WorkTypeSelectAll        = "/pc/work/type/select/all"
	WorkTypeDelete           = "/pc/work/type/delete"
)

func Run(port string, mux *http.ServeMux) {
	//Apis["/"] = test

	//公共部分
	Apis[PublicFileUpload] = PublicFileUploadHttp
	Apis[PublicFileDelete] = PublicFileDeleteHttp
	Apis[PublicFileUploadChat] = PublicFileUploadChatHttp
	Apis[PublicDatabaseBackups] = DatabaseBackupsHttp
	Apis[PublicDatabaseRestore] = DatabaseRestoreHttp
	//用户相关
	Apis[UserRegister] = UserRegisterHttp
	Apis[UserLogin] = UserLoginHttp
	Apis[UserUpdate] = UserUpdateHttp
	Apis[UserDelete] = UserDeleteHttp
	Apis[UserSelectAll] = UserSelectAllHttp
	Apis[UserSelect] = UserSelectByUserIdHttp
	Apis[UserToStructureTreeAdd] = UserToStructureTreeAddHttp
	Apis[UserToStructureTreeSelectAll] = UserToStructureTreeSelectAllHttp
	//权限相关
	Apis[PermissionAdd] = PermissionAddHttp
	Apis[PermissionUpdate] = PermissionUpdateHttp
	Apis[PermissionDelete] = PermissionDeleteHttp
	Apis[PermissionSelect] = PermissionSelectHttp
	Apis[PermissionSelectList] = PermissionSelectListHttp
	Apis[PermissionToStructureTreeAdd] = PermissionToStructureTreeAddHttp
	Apis[PermissionToStructureTreeDelete] = PermissionToStructureTreeDeleteHttp
	Apis[PermissionToStructureTreeSelect] = PermissionToStructureTreeSelectHttp
	Apis[CharacterAdd] = CharacterAddHttp
	Apis[CharacterSelectAll] = CharacterSelectAllHttp
	Apis[CharacterDelete] = CharacterDeleteHttp
	//组织结构树相关
	Apis[StructureTreeNodeCreate] = StructureTreeNodeCreateHttp
	Apis[StructureTreeNodeDelete] = StructureTreeNodeDeleteHttp
	Apis[StructureTreeNodeUpdate] = StructureTreeNodeUpdateHttp
	Apis[StructureTreeNodeSelectChild] = StructureTreeChildNodeSelectHttp
	Apis[StructureTreeNodeSelectChildAll] = StructureTreeChildNodeSelectAllHttp
	//项目树相关
	Apis[ProjectTreeNodeCreate] = ProjectTreeNodeCreateHttp
	Apis[ProjectTreeNodeCreateApplyFor] = ProjectTreeNodeApplyForCreateHttp
	Apis[ProjectTreeNodeAddStructure] = ProjectTreeNodeAddStructureHttp
	Apis[ProjectTreeNodeDelete] = ProjectTreeNodeDeleteHttp
	Apis[ProjectTreeNodeUpdate] = ProjectTreeNodeUpdateHttp
	Apis[ProjectTreeChildNodeSelect] = ProjectTreeChildNodeSelectHttp
	Apis[ProjectTreeChildNodeSelectAll] = ProjectTreeChildNodeSelectAllHttp
	Apis[ProjectTreeUserAdd] = ProjectTreeUserAddHttp
	Apis[ProjectTreeUserDelete] = ProjectTreeUserDeleteHttp
	Apis[ProjectTreeUserSelect] = ProjectTreeUserSelectHttp
	Apis[ProjectTreeUserSelectAll] = ProjectTreeUserSelectAllHttp
	Apis[ProjectTreeUserSelectProject] = ProjectTreeUserSelectProjectHttp
	//文件树相关
	Apis[FileTreeNodeCreate] = FileTreeNodeCreateHttp
	Apis[FileTreeNodeDelete] = FileTreeNodeDeleteHttp
	Apis[FileTreeNodeUpdate] = FileTreeNodeUpdateHttp
	Apis[FileTreeNodeSelectChild] = FileTreeChildNodeSelectHttp
	Apis[FileTreeNodeSelectChildAll] = FileTreeChildNodeSelectAllHttp
	Apis[FileTreeFileAdd] = FileTreeFileAddHttp
	Apis[FileTreeFileSelect] = FileTreeFileSelectHttp
	Apis[FileTreeFileCommissioned] = FileTreeFileCommissionedHttp
	Apis[FileTreeFileCommissionedSelect] = FileTreeFileCommissionedSelectHttp
	//考勤相关
	Apis[AttendancePunchIn] = AttendancePunchInHttp
	Apis[AttendancePunchOut] = AttendancePunchOutHttp
	Apis[AttendanceSelect] = AttendanceSelectHttp
	Apis[AttendanceAskForLeaveCreate] = AttendanceAskForLeaveCreateHttp
	Apis[AttendanceAskForLeaveSelectById] = AttendanceAskForLeaveSelectByIdHttp
	Apis[AttendanceAskForLeaveSelectByUserId] = AttendanceAskForLeaveSelectByUserIdHttp
	Apis[AttendanceAskForLeaveApproval] = AttendanceAskForLeaveApprovalHttp
	Apis[AttendanceAskForLeaveApprovalSelect] = AttendanceAskForLeaveApprovalSelectHttp
	//消息相关
	Apis[MessageSelect] = MessageSelectHttp
	Apis[MessageRead] = MessageReadHttp
	Apis[MessageDelete] = MessageDeleteHttp
	//聊天消息相关
	Apis[ChatMessageSend] = ChatMessageSendHttp
	Apis[ChatMessageDelete] = ChatMessageDeleteHttp
	Apis[ChatMessageSelectTome] = ChatMessageSelectToMeHttp
	//合同相关
	Apis[ContractCreate] = ContractCreateHttp
	Apis[ContractUpdate] = ContractUpdateHttp
	Apis[ContractDelete] = ContractDeleteHttp
	Apis[ContractSelectByNo] = ContractSelectByNoHttp
	Apis[ContractSelectByVague] = ContractSelectByVagueHttp
	Apis[ContractSelectByTime] = ContractSelectByTimeHttp
	Apis[ContractAdditionalAdd] = ContractAdditionalAddHttp
	Apis[ContractAdditionalSelect] = ContractAdditionalSelectHttp
	Apis[ContractAdditionalUpdate] = ContractAdditionalUpdateHttp
	Apis[ContractAdditionalDelete] = ContractAdditionalDeleteHttp
	Apis[ContractTypeCreate] = ContractTypeCreateHttp
	Apis[ContractTypeSelectAll] = ContractTypeSelectAllHttp
	Apis[ContractYearSelectAll] = ContractYearSelectAllHttp
	Apis[ContractTypeDelete] = ContractTypeDeleteHttp
	Apis[WorkTypeCreate] = WorkTypeCreateHttp
	Apis[WorkTypeSelectAll] = WorkTypeSelectAllHttp
	Apis[WorkTypeDelete] = WorkTypeDeleteHttp

	Apis[UploadWorkTime] = UploadWorkTimeHttp
	Apis[GetWorkTime] = GetWorkTimeHttp
	httpUtils.FileHandle(mux, code.RootName, code.RootPath)
	for k, v := range Apis {
		mux.HandleFunc(k, AppHandleFunc(v))
	}
	loge.SetHttp(mux)
	_ = update.UpgradeService(":"+port, mux)
}

var Apis = make(map[string]AppHandleFuncErr, 10)

type AppHandleFuncErr func(w http.ResponseWriter, r *http.Request) error
type FileHandler struct{}

func (f FileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	values, _ := url.PathUnescape(r.URL.String())
	fileName := code.RootPath + values
	if fileUtil.PathExists(fileName) {
		f, _ := os.Stat(fileName)
		if !f.IsDir() {
			http.ServeFile(w, r, fileName)
			return
		}
	}
	http.NotFound(w, r)
}

func AppHandleFunc(appHandle AppHandleFuncErr) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			i := recover()
			if resultData, ok := i.(*bean.ResultData); ok {
				resultData.WriterResponse(w)
			} else if err, ok := i.(error); ok {
				//data := bean.NewErrorMessage("服务器内部错误")
				data := bean.NewErrorMessage(err.Error())
				data.DebugMessage = fmt.Sprintf("%v", err)
				data.WriterResponse(w)
				loge.W(r.URL, err)
			}
		}()
		err := appHandle(w, r)
		loge.WDf("请求url%v,请求数据:%v", r.URL, r.Form)
		loge.WDf("返回数据----->%v", err)
		if resultData, ok := err.(*bean.ResultData); ok {
			resultData.WriterResponse(w)
		} else if err != nil {
			//data := bean.NewErrorMessage("服务器内部错误")
			data := bean.NewErrorMessage(err.Error())
			data.DebugMessage = fmt.Sprintf("%v", err)
			data.WriterResponse(w)
			loge.W(r.URL, err)
		}
	}
}
